<template>
  <div class="order-detail">
    <div class="header">
      <h1>订单详情</h1>
      <el-button @click="goBack">返回</el-button>
    </div>
    
    <el-card class="order-info-card">
      <div class="order-status">
        <h2>订单状态：{{ getOrderStatusText(order.status) }}</h2>
      </div>
      
      <div class="order-basic-info">
        <div class="info-item">
          <span class="info-label">订单编号：</span>
          <span class="info-value">{{ order.orderNo }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">创建时间：</span>
          <span class="info-value">{{ formatDate(order.createdAt) }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">支付方式：</span>
          <span class="info-value">{{ getPaymentMethodText(order.paymentMethod) }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">支付时间：</span>
          <span class="info-value">{{ order.paymentTime ? formatDate(order.paymentTime) : '未支付' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">完成时间：</span>
          <span class="info-value">{{ order.completedTime ? formatDate(order.completedTime) : '未完成' }}</span>
        </div>
      </div>
    </el-card>
    
    <el-card class="shipping-address-card">
      <div class="card-title">收货地址</div>
      <div class="address-info" v-if="order.shippingAddress">
        <div class="address-name">{{ order.shippingAddress.receiverName }}</div>
        <div class="address-phone">{{ order.shippingAddress.receiverPhone }}</div>
        <div class="address-detail">{{ order.shippingAddress.province }}{{ order.shippingAddress.city }}{{ order.shippingAddress.district }}{{ order.shippingAddress.address }}</div>
      </div>
    </el-card>
    
    <el-card class="order-items-card">
      <div class="card-title">商品信息</div>
      <div class="order-items">
        <div 
          v-for="item in order.orderItems" 
          :key="item.id" 
          class="order-item"
          @click="goToProductDetail(item.productId)"
        >
          <img :src="item.imageUrl" alt="商品图片" class="item-image">
          <div class="item-info">
            <div class="item-name">{{ item.productName }}</div>
            <div class="item-price">¥{{ item.price.toFixed(2) }}</div>
            <div class="item-quantity">x{{ item.quantity }}</div>
          </div>
        </div>
      </div>
    </el-card>
    
    <el-card class="order-amount-card">
      <div class="card-title">金额信息</div>
      <div class="amount-info">
        <div class="amount-item">
          <span class="amount-label">商品总价：</span>
          <span class="amount-value">¥{{ order.totalAmount.toFixed(2) }}</span>
        </div>
        <div class="amount-item">
          <span class="amount-label">运费：</span>
          <span class="amount-value">¥{{ order.shippingFee.toFixed(2) }}</span>
        </div>
        <div class="amount-item total">
          <span class="amount-label">实付金额：</span>
          <span class="amount-value">¥{{ (order.totalAmount + order.shippingFee).toFixed(2) }}</span>
        </div>
      </div>
    </el-card>
    
    <div class="order-actions" v-if="order.status !== 4 && order.status !== 5">
      <template v-if="order.status === 0">
        <el-button type="primary" @click="handlePay">去支付</el-button>
        <el-button type="danger" @click="handleCancel">取消订单</el-button>
      </template>
      <template v-else-if="order.status === 2">
        <el-button type="primary" @click="handleConfirm">确认收货</el-button>
      </template>
      <template v-else-if="order.status === 3">
        <el-button type="primary">评价商品</el-button>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { orderService } from '../services/orderService'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../store'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 订单ID
const orderId = ref(route.params.id)

// 订单数据
const order = ref({
  id: '',
  orderNo: '',
  status: 0,
  paymentMethod: 0,
  totalAmount: 0,
  shippingFee: 0,
  createdAt: '',
  paymentTime: '',
  completedTime: '',
  shippingAddress: null,
  orderItems: []
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    0: '待付款',
    1: '待发货',
    2: '待收货',
    3: '待评价',
    4: '已完成',
    5: '已取消',
    6: '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const methodMap = {
    0: '未支付',
    1: '微信支付',
    2: '支付宝',
    3: '银行卡支付',
    4: '货到付款'
  }
  return methodMap[method] || '未知支付方式'
}

// 加载订单详情
const loadOrderDetail = async () => {
  try {
    if (!userStore.isAuthenticated) {
      ElMessage.warning('请先登录')
      // 不自动跳转到登录页，而是让用户决定
      // router.push('/login')
      return
    }
    
    const result = await orderService.getOrderDetail(orderId.value)
    order.value = result.data || {
      id: '',
      orderNo: '',
      status: 0,
      paymentMethod: 0,
      totalAmount: 0,
      shippingFee: 0,
      createdAt: '',
      paymentTime: '',
      completedTime: '',
      shippingAddress: null,
      orderItems: []
    }
  } catch (error) {
    console.error('加载订单详情失败:', error)
    
    // 根据错误类型提供更友好的错误提示
    if (error.response) {
      // 服务器返回的错误
      switch (error.response.status) {
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          // 显示登录对话框，而不是自动跳转
          ElMessageBox.confirm('登录已过期，是否重新登录？', '提示', {
            confirmButtonText: '去登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            router.push('/login')
          }).catch(() => {
            // 用户选择不登录，不做任何操作
          })
          break
        case 403:
          ElMessage.error('无权限访问订单信息')
          break
        case 404:
          ElMessage.error('订单不存在或已被删除')
          break
        case 500:
          ElMessage.error('服务器错误，请稍后再试')
          break
        default:
          ElMessage.error(`加载订单详情失败: ${error.response.data.message || '未知错误'}`)
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      // 请求设置出错
      ElMessage.error(`加载订单详情失败: ${error.message}`)
    }
  }
}

// 去支付
const handlePay = async () => {
  try {
    // 这里应该调用支付接口
    await orderService.payOrder(order.value.id, 1) // 1代表微信支付
    ElMessage.success('支付成功')
    loadOrderDetail()
  } catch (error) {
    console.error('支付失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      ElMessage.error('登录已过期，请重新登录')
      ElMessageBox.confirm('登录已过期，是否重新登录？', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        router.push('/login')
      }).catch(() => {
        // 用户选择不登录，不做任何操作
      })
    } else {
      ElMessage.error('支付失败，请重试')
    }
  }
}

// 取消订单
const handleCancel = async () => {
  try {
    await orderService.cancelOrder(order.value.id)
    ElMessage.success('订单已取消')
    loadOrderDetail()
  } catch (error) {
    console.error('取消订单失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      ElMessage.error('登录已过期，请重新登录')
      ElMessageBox.confirm('登录已过期，是否重新登录？', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        router.push('/login')
      }).catch(() => {
        // 用户选择不登录，不做任何操作
      })
    } else {
      ElMessage.error('取消订单失败，请重试')
    }
  }
}

// 确认收货
const handleConfirm = async () => {
  try {
    await orderService.updateOrderStatus(order.value.id, 4)
    ElMessage.success('已确认收货')
    loadOrderDetail()
  } catch (error) {
    console.error('确认收货失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      ElMessage.error('登录已过期，请重新登录')
      ElMessageBox.confirm('登录已过期，是否重新登录？', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        router.push('/login')
      }).catch(() => {
        // 用户选择不登录，不做任何操作
      })
    } else {
      ElMessage.error('确认收货失败，请重试')
    }
  }
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 页面加载时初始化数据
onMounted(() => {
  loadOrderDetail()
})
</script>

<style scoped>
.order-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  font-size: 28px;
}

.order-info-card {
  margin-bottom: 20px;
}

.order-status {
  text-align: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.order-status h2 {
  font-size: 20px;
  color: #ff4d4f;
}

.order-basic-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 20px;
}

.info-item {
  display: flex;
  gap: 10px;
  min-width: 250px;
}

.info-label {
  font-weight: bold;
  color: #666;
}

.info-value {
  color: #333;
}

.shipping-address-card,
.order-items-card,
.order-amount-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.address-info {
  padding: 20px;
}

.address-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.address-phone {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.address-detail {
  font-size: 14px;
  line-height: 1.6;
}

.order-items {
  padding: 20px;
}

.order-item {
  display: flex;
  gap: 15px;
  cursor: pointer;
  padding: 10px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
  margin-bottom: 10px;
}

.order-item:hover {
  background-color: #f5f5f5;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: contain;
}

.item-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.item-name {
  font-size: 14px;
  margin-bottom: 5px;
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-price {
  font-size: 16px;
  color: #ff4d4f;
  margin-bottom: 5px;
}

.item-quantity {
  font-size: 14px;
  color: #666;
}

.amount-info {
  padding: 20px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.amount-item.total {
  font-size: 18px;
  font-weight: bold;
  border-bottom: none;
}

.amount-label {
  color: #666;
}

.amount-value {
  color: #333;
}

.amount-item.total .amount-value {
  color: #ff4d4f;
}

.order-actions {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-top: 30px;
}
</style>